<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  type MyNoticeSearchParams,
  Notice,
  type UserNotice,
  fetchMyNoticePage,
  fetchNoticeDetail,
  readAllNotice,
} from "@/service/api";
import { DICT_TYPE } from "@/utils/dict";
import { useBoolean } from "~/packages/hooks/src";
import { $t } from "@/locales";
import NoticeDetailModal from "../../../../views/manage/notice/modules/notice-detail-modal.vue";
import { useRouterPush } from "@/hooks/common/router";

const { routerPushByKey } = useRouterPush();

const activeTabName = ref("notice");
const notices = ref<UserNotice[]>([]);

const { bool: noticeDetailVisible, setTrue: openNoticeDetailModal } =
  useBoolean();

const rowDataNotice = ref<Notice>();

// 阅读通知公告
async function readNotice(id: number) {
  const { error, data: noticeDetail } = await fetchNoticeDetail(id);
  if (!error) {
    rowDataNotice.value = noticeDetail;
    openNoticeDetailModal();

    const index = notices.value.findIndex((notice) => notice.id === id);
    if (index >= 0) {
      notices.value.splice(index, 1); // 从消息列表中移除已读消息
    }
  } else {
    window.$message?.error($t("common.noData"));
  }
}

/** 获取未读消息列表并连接 WebSocket */
onMounted(() => {
  // 获取通知列表
  const param: MyNoticeSearchParams = {
    current: 1,
    size: 99,
    isRead: 0,
  };
  fetchMyNoticePage(param).then((res) => {
    notices.value = res.data?.records || [];
  });
});

function handleTabsUpdateValue(value: string) {
  activeTabName.value = value;
}
/**
 * 查看更多
 */
function viewMore() {
  routerPushByKey("my-notice");
}

/**
 * 全部已读
 */
async function markAllAsRead() {
  const { error } = await readAllNotice();
  if (!error) {
    notices.value = [];
  }
}
</script>

<template>
  <div class="message">
    <NPopover trigger="hover">
      <template #trigger>
        <div class="h-full w-full">
          <NBadge
            v-if="notices.length > 0"
            :value="notices.length"
            :offset="[-10, 5]"
            :max="99"
          >
            <ButtonIcon>
              <icon-ep:bell />
            </ButtonIcon>
          </NBadge>
          <NBadge v-else>
            <ButtonIcon>
              <icon-ep:bell />
            </ButtonIcon>
          </NBadge>
        </div>
      </template>
      <div class="p-2">
        <NTabs trigger="hover" @update:value="handleTabsUpdateValue">
          <NTabPane :tab="$t('header.notice.notice')" name="notice">
            <div class="h82 w-180 overflow-auto notice-list-card">
              <div v-if="notices.length > 0">
                <div v-for="item in notices" :key="item.id">
                  <div
                    class="flex items-center justify-between cursor-pointer hover:(bg-gray bg-opacity-10 rounded-md) pt-2 pb-2 pr-2"
                    @click="readNotice(item.id)"
                  >
                    <div>
                      <DictTag
                        class="ml-5 truncate text-center"
                        :type="DICT_TYPE.SYSTEM_NOTICE_TYPE"
                        :value="item.type"
                      />
                    </div>
                    <NEllipsis class="w-100">
                      {{ item.title }}
                    </NEllipsis>
                    <div>
                      {{ item.publishTime }}
                    </div>
                  </div>
                  <br />
                </div>
              </div>
              <div v-else>
                <NEmpty :description="$t('header.notice.noNotice')" />
              </div>
            </div>
          </NTabPane>
          <NTabPane :tab="$t('header.notice.message')" name="message">
            <div class="h82 w-180 overflow-auto notice-list-card">
              <div>
                <NEmpty :description="$t('header.notice.noMessage')" />
              </div>
            </div>
          </NTabPane>
          <NTabPane :tab="$t('header.notice.backlog')" name="task">
            <div class="h82 w-180 overflow-auto notice-list-card">
              <div>
                <NEmpty :description="$t('header.notice.noBacklog')" />
              </div>
            </div>
          </NTabPane>
        </NTabs>
        <div v-if="notices.length > 0 && activeTabName === 'notice'">
          <NDivider />
          <div class="h-2rem leading-8 hover:(opacity-70 rounded-md)">
            <div class="float-left h-2rem leading-8" @click="viewMore">
              <NButton text type="primary" icon-placement="right">
                <template #icon>
                  <icon-uil:angle-right-b />
                </template>
                <span class="text-xs">{{ $t("header.notice.readMore") }}</span>
              </NButton>
            </div>
            <div class="float-right h-2rem leading-8" @click="markAllAsRead">
              <NButton text type="primary">
                <span class="text-xs">{{ $t("header.notice.readAll") }}</span>
              </NButton>
            </div>
          </div>
        </div>
      </div>
    </NPopover>

    <NoticeDetailModal
      v-model:visible="noticeDetailVisible"
      :row-data="rowDataNotice"
    />
  </div>
</template>

<style scoped>
.notice-list-card::-webkit-scrollbar {
  width: 4px;
  height: 10px;
}

.notice-list-card::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}

.notice-list-card::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}

.notice-list-card::-webkit-scrollbar-thumb:hover {
  background: #333;
}

.notice-list-card::-webkit-scrollbar-corner {
  background: #179a16;
}
</style>
